package com.hkts.beltweigher.synchronizationtask;

import com.google.common.collect.Lists;
import com.hkts.beltweigher.master.entity.*;
import com.hkts.beltweigher.master.mapper.ScaleDataMapper;
import com.hkts.beltweigher.master.mapper.YbClassesAccumulateMapper;
import com.hkts.beltweigher.master.mapper.YbHourAccumulateMapper;
import com.hkts.beltweigher.master.mapper.YbRunAccumulateMapper;
import com.hkts.beltweigher.master.service.*;
import com.hkts.beltweigher.salve.entity.EastBeltscalesCumulativedata;
import com.hkts.beltweigher.salve.entity.EastBeltscalesInstantaneousdata;
import com.hkts.beltweigher.salve.entity.EastBeltscalesMinitue;
import com.hkts.beltweigher.salve.service.IEastBeltscalesCumulativedataService;
import com.hkts.beltweigher.salve.service.IEastBeltscalesInstantaneousdataService;
import com.hkts.beltweigher.salve.service.IEastBeltscalesMinitueService;
import com.hkts.beltweigher.utils.DateUtil;
import com.hkts.beltweigher.utils.SnowFlakeUtil;
import com.hkts.beltweigher.utils.StringUtil;
import com.hkts.beltweigher.websocket.MyChannelHandlerPool;
import com.hkts.beltweigher.websocket.sendUtil.NettySendUtil;
import com.hkts.beltweigher.websocket.sendUtil.ResultMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.DoubleStream;

import static com.hkts.beltweigher.synchronizationtask.HomePageCache.homeCache;

@Component
@Transactional
@Slf4j
public class SyncBeltWeigherUtil {

    @Autowired
    private IMatchsAllocationService iMatchsAllocationService;
    @Autowired
    private IHktsFieldControlService iHktsFieldControlService;
    @Autowired
    private IDisplaydataService iDisplaydataService;
    @Autowired
    private IScaleDataService iScaleDataService;
    @Autowired
    private ScaleDataMapper scaleDataMapper;
    @Autowired
    private IYbHourAccumulateService iYbHourAccumulateService;
    @Autowired
    private IYbRunAccumulateService iYbRunAccumulateService;
    @Autowired
    private YbHourAccumulateMapper ybHourAccumulateMapper;
    @Autowired
    private YbClassesAccumulateMapper ybClassesAccumulateMapper;
    @Autowired
    private YbRunAccumulateMapper ybRunAccumulateMapper;
    @Autowired
    private IRandomNumberSettingsService iRandomNumberSettingsService;
    @Autowired
    private IInstrumentControlService iInstrumentControlService;
    @Autowired
    private IRegularTimeService iRegularTimeService;
    @Autowired
    private IEastBeltscalesInstantaneousdataService iEastBeltscalesInstantaneousdataService;
    @Autowired
    private IEastBeltscalesMinitueService iEastBeltscalesMinitueService;
    @Autowired
    private IEastBeltscalesCumulativedataService iEastBeltscalesCumulativedataService;



    /**
     * 配料设置更新
     */

    /*public void syncMatchsData() {

        //查询远程配料比例设置
        List<Map> matchsList = iMatchsService.selectMatchsMap();

        //数据同步
        for (int i = 0; i < matchsList.size(); i++) {
            MatchsAllocation matchsAllocation = new MatchsAllocation();
            matchsAllocation.setId(Integer.parseInt(matchsList.get(i).get("ID").toString()));
            matchsAllocation.setTotalRate(matchsList.get(i).get("TotalRate").toString());
            matchsAllocation.setiType(Integer.parseInt(matchsList.get(i).get("iType").toString()));
            matchsAllocation.setMaterial(matchsList.get(i).get("Material").toString());
            String s = StringUtil.changeString(matchsList.get(i).get("SetMatch").toString(), Float.parseFloat(matchsList.get(i).get("TotalRate").toString()));
            matchsAllocation.setSetTraffic(matchsList.get(i).get("SetFlow").toString());
            matchsAllocation.setSetRatio(matchsList.get(i).get("SetMatch").toString());
            iMatchsAllocationService.updateById(matchsAllocation);
        }

    }

    *//**
     * 页面展示数据更新
     *//*
    public void syncDisplayData() {

        //查询远程实时数据
        List<Map> displayData = iDisplayDataService.selectDisplayData();
        //查询配料比例数据，最后组装数据使用
        MatchsAllocation byId = iMatchsAllocationService.getById(1);
        Displaydata displaydata = new Displaydata();

        List<Displaydata> displaydataList = iDisplaydataService.selectList(displaydata);
        //同步实时数据
        for (int i = 0; i < displayData.size(); i++) {
            LocalDateTime updateTime = DateUtil.convertLocalDateTime(displayData.get(i).get("修改日期").toString() + "T" + displayData.get(i).get("修改时间").toString());
            LocalDateTime updateDate = DateUtil.convertDate(displayData.get(i).get("修改日期").toString());

            Displaydata displayDataMaster = new Displaydata();
            displayDataMaster.setId(Integer.parseInt(displayData.get(i).get("序号").toString()));
            displayDataMaster.setDayAccumulation(Float.parseFloat(displayData.get(i).get("日累计").toString()));
            displayDataMaster.setDataStatus(Integer.parseInt(displayData.get(i).get("通讯状态").toString()));
            //实时计算累计量
            if (displaydataList.get(i).getInitAccumulate() != null) {
                displayDataMaster.setAccumulate(displaydataList.get(i).getInitAccumulate() + Float.parseFloat(displayData.get(i).get("班累计").toString()));
            }
            displayDataMaster.setFlowValue(Float.parseFloat(displayData.get(i).get("流量值").toString()));
            displayDataMaster.setClassAccumulation(Float.parseFloat(displayData.get(i).get("班累计").toString()));
            displayDataMaster.setHourlyAccumulation(Float.parseFloat(displayData.get(i).get("时累计").toString()));
            displayDataMaster.setInstrumentName(displayData.get(i).get("名称").toString());
            displayDataMaster.setRemark(displayData.get(i).get("备注").toString());
            displayDataMaster.setSpeedValue(Float.parseFloat(displayData.get(i).get("速度值").toString()));
            displayDataMaster.setUpdadeTime(updateTime);
            displayDataMaster.setUpdateDate(updateDate);
            iDisplaydataService.updateById(displayDataMaster);
        }


        //开关设置
        for (int i = 0; i < displaydataList.size(); i++) {
            if (displaydataList.get(i).getSwitchStatus() != null && !iInstrumentControlService.getInstrumentStatus().get(displaydataList.get(i).getId()).equals(displaydataList.get(i).getSwitchStatus().toString())) {
                //开关设置同步，若状态为关，将实时Copy数据修改为暂停时数据
                displaydataList.get(i).setSwitchStatus(Integer.parseInt(iInstrumentControlService.getInstrumentStatus().get(displaydataList.get(i).getId())));
                if (iInstrumentControlService.getInstrumentStatus().get(displaydataList.get(i).getId()).equals(EnviromentConstance.IS_NOT_ENABLE)) {
                    displaydataList.get(i).setAccumulateCopy(displaydataList.get(i).getAccumulate());
                    displaydataList.get(i).setClassAccumulationCopy(displaydataList.get(i).getClassAccumulation());
                    displaydataList.get(i).setDayAccumulationCopy(displaydataList.get(i).getDayAccumulation());
                    displaydataList.get(i).setHourlyAccumulationCopy(displaydataList.get(i).getHourlyAccumulation());
                    displaydataList.get(i).setFlowValueCopy(0.0f);
                    displaydataList.get(i).setSpeedValueCopy(0.0f);
                }
                iDisplaydataService.saveOrUpdate(displaydataList.get(i));
            }
        }
        List<Map<String, String>> resultMaps = new ArrayList<>();

        //组装数据websocket消息
        for (int i = 0; i < displaydataList.size(); i++) {
            //开关关闭状态
            if (displaydataList.get(i).getSwitchStatus() != null && displaydataList.get(i).getSwitchStatus() == 0) {
                Map<String, String> map = new HashMap<>();
                map.put("id", displaydataList.get(i).getId().toString());
                map.put("instrumentName", displaydataList.get(i).getInstrumentName());
                map.put("accumulate", displaydataList.get(i).getAccumulateCopy().toString());
                map.put("flowValue", displaydataList.get(i).getFlowValueCopy().toString());
                map.put("speedValue", displaydataList.get(i).getSpeedValueCopy().toString());
                map.put("hourlyAccumulation", displaydataList.get(i).getHourlyAccumulationCopy().toString());
                map.put("classAccumulation", displaydataList.get(i).getClassAccumulationCopy().toString());
                resultMaps.add(map);
                //开关开启状态
            } else if (displaydataList.get(i).getSwitchStatus() != null && displaydataList.get(i).getSwitchStatus() == 1) {
                Map<String, String> map = new HashMap<>();
                map.put("id", displaydataList.get(i).getId().toString());
                map.put("instrumentName", displaydataList.get(i).getInstrumentName());
                map.put("accumulate", displaydataList.get(i).getAccumulate().toString());
                map.put("flowValue", displaydataList.get(i).getFlowValue().toString());
                map.put("speedValue", displaydataList.get(i).getSpeedValue().toString());
                map.put("hourlyAccumulation", displaydataList.get(i).getHourlyAccumulation().toString());
                map.put("classAccumulation", displaydataList.get(i).getClassAccumulation().toString());
                resultMaps.add(map);
            }
        }
        //将配料比例拆分重组放入websocket数据中
        String[] split = byId.getSetTraffic().split(":");
        for (int i = 0; i < split.length; i++) {
            resultMaps.get(i).put("setTraffic", split[i]);
        }


        List<Map> resultMapList = new ArrayList<>();
        Map<String, String> collect = resultMaps.stream()
                .collect(Collectors.toMap(
                        map -> map.get("id"),
                        map -> map.get("instrumentName")
                ));
        resultMapList.add(collect);
        Map<String, String> collect1 = resultMaps.stream()
                .collect(Collectors.toMap(
                        map -> map.get("id"),
                        map -> map.get("accumulate")
                ));
        resultMapList.add(collect1);
        Map<String, String> collect2 = resultMaps.stream()
                .collect(Collectors.toMap(
                        map -> map.get("id"),
                        map -> map.get("flowValue")
                ));
        resultMapList.add(collect2);
        Map<String, String> collect3 = resultMaps.stream()
                .collect(Collectors.toMap(
                        map -> map.get("id"),
                        map -> map.get("speedValue")
                ));
        resultMapList.add(collect3);

        Map<String, String> collect7 = resultMaps.stream()
                .collect(Collectors.toMap(
                        map -> map.get("id"),
                        map -> map.get("setTraffic")
                ));
        resultMapList.add(collect7);

        Map<String, String> collect4 = resultMaps.stream()
                .collect(Collectors.toMap(
                        map -> map.get("id"),
                        map -> map.get("hourlyAccumulation")
                ));
        resultMapList.add(collect4);
        Map<String, String> collect5 = resultMaps.stream()
                .collect(Collectors.toMap(
                        map -> map.get("id"),
                        map -> map.get("classAccumulation")
                ));
        resultMapList.add(collect5);


        //homeCache.put("0", id);
        //发送消息
        ResultMsg msg = new ResultMsg();
        msg.setCode("200");
        msg.setMessage(resultMapList);
        NettySendUtil.sendAllMessage(msg, MyChannelHandlerPool.channelGroup);
    }


    *//**
     * 字段控制
     *
     * @param hktsHeatItems
     * @param matchsList
     * @return
     *//*
    public List<Map> fieldControl(List<HktsHeatItem> hktsHeatItems, List<Map> matchsList) {

        HktsFieldControl control = new HktsFieldControl();
        List<HktsFieldControl> hktsFieldControls = iHktsFieldControlService.selectList(control);
        Map<String, HktsFieldControl> fieldControlMap = hktsFieldControls.stream().collect(Collectors.toMap(HktsFieldControl::getItemId, Function.identity()));
        for (int i = 0; i < matchsList.size(); i++) {
            for (int i1 = 0; i1 < hktsHeatItems.size(); i1++) {
                Object o = matchsList.get(i).get(hktsHeatItems.get(i1).getCorrespondingField());
                if (hktsHeatItems.get(i1).getNeedDeal().equals(EnviromentConstance.COEFFICIENT)) {
                    float coefficent = Float.parseFloat(fieldControlMap.get(hktsHeatItems.get(i1).getId()).getCoefficient().toString());
                    if (o != null) {
                        matchsList.get(i).put(hktsHeatItems.get(i1).getCorrespondingField(), coefficent * Float.parseFloat(o.toString()));
                    }
                }
            }
        }
        return matchsList;

    }

    //分钟数据更新
    public void syncIsLqxData() {
        //查询本地分钟数据
        ScaleData scaleDataLast = iScaleDataService.selectScaleData();
        List<ScaleData> scaleDataList = new ArrayList<>();
        if (scaleDataLast != null) {
            //获取本地数据最后一条时分秒
            String strTime = DateUtil.getStrTime(scaleDataLast.getCreateTime());
            //获取表名
            LocalDate date = LocalDate.parse(scaleDataLast.getCreateData());
            int year = date.getYear();
            String tableName = "Slqx" + year;
            List<Map> slqx2024sAll = new ArrayList<>();
            //如果当前时间大于23:59就获取第二天00：的数据
            if (DateUtil.getMaxTime(strTime)) {
                String nextDay = DateUtil.getNextDay(scaleDataLast.getCreateData());
                List<Map> slqx2024ByRqAndSj = iSlqx2024Service.getSlqx2024ByRqAndSj(tableName, nextDay, "00:00:00");
                slqx2024sAll.addAll(slqx2024ByRqAndSj);
            } else {
                //等于当前日期大于时分秒的数据
                List<Map> slqx2024ByRqAndSj = iSlqx2024Service.getSlqx2024ByRqAndSj(tableName, scaleDataLast.getCreateData(), strTime);
                slqx2024sAll.addAll(slqx2024ByRqAndSj);
            }
            //大于当前日期的数据
            List<Map> slqx2024ByRq = iSlqx2024Service.getSlqx2024ByRq(tableName, scaleDataLast.getCreateData());
            if (slqx2024ByRq.size() > 0) {
                slqx2024sAll.addAll(slqx2024ByRq);
            }

            //数据同步
            for (int i = 0; i < slqx2024sAll.size(); i++) {
                ScaleData scaleData = new ScaleData();
                scaleData.setCreateData(slqx2024sAll.get(i).get("rq").toString());
                scaleData.setCreateTime(DateUtil.convertLocalDateTime(slqx2024sAll.get(i).get("rq").toString() + "T" + slqx2024sAll.get(i).get("sj").toString()));
                scaleData.setB1(Float.parseFloat(slqx2024sAll.get(i).get("B1").toString()));
                scaleData.setB2(Float.parseFloat(slqx2024sAll.get(i).get("B2").toString()));
                scaleData.setB3(Float.parseFloat(slqx2024sAll.get(i).get("B3").toString()));
                scaleData.setB4(Float.parseFloat(slqx2024sAll.get(i).get("B4").toString()));
                scaleData.setB5(Float.parseFloat(slqx2024sAll.get(i).get("B5").toString()));
                scaleDataList.add(scaleData);
            }
        } else {
            //所有数据同步
            List<Map> slqx2023ListAll = iSlqx2024Service.getSlqx2023ListAll();
            List<Map> slqx2024ListAll = iSlqx2024Service.getSlqx2024ListAll();
            slqx2023ListAll.addAll(slqx2024ListAll);
//            List<Map> slqxListAllMap = fieldControl(hktsHeatItems, slqx2023ListAll);
            for (int i = 0; i < slqx2023ListAll.size(); i++) {
                ScaleData scaleData = new ScaleData();
                scaleData.setCreateData(slqx2023ListAll.get(i).get("rq").toString());
                scaleData.setCreateTime(DateUtil.convertLocalDateTime(slqx2023ListAll.get(i).get("rq").toString() + "T" + slqx2023ListAll.get(i).get("sj").toString()));
                scaleData.setB1(Float.parseFloat(slqx2023ListAll.get(i).get("B1").toString()));
                scaleData.setB2(Float.parseFloat(slqx2023ListAll.get(i).get("B2").toString()));
                scaleData.setB3(Float.parseFloat(slqx2023ListAll.get(i).get("B3").toString()));
                scaleData.setB4(Float.parseFloat(slqx2023ListAll.get(i).get("B4").toString()));
                scaleData.setB5(Float.parseFloat(slqx2023ListAll.get(i).get("B5").toString()));
                scaleDataList.add(scaleData);
            }
        }
        if (scaleDataList.size() > 100000) {
            List<List<ScaleData>> partition = Lists.partition(scaleDataList, 1000);
            for (List<ScaleData> list : partition) {
                scaleDataMapper.batchInsert(list);
            }
        } else if (scaleDataList.size() < 100000 && scaleDataList.size() > 0) {
            scaleDataMapper.batchInsert(scaleDataList);
        }

    }

    //小时数据更新
    public void syncYbHourAccumulateData() {
        //获取最后一条小时数据
        YbHourAccumulate ybHourAccumulateLast = iYbHourAccumulateService.selectYbHourAccumulate();

        List<YbHourAccumulate> accumulateList = new ArrayList<>();
        //同步新数据
        if (ybHourAccumulateLast != null) {
            //TODO 更新数据
            Integer id = ybHourAccumulateLast.getId();
            List<Map> ybHourLeiJiListGt = iYbHourLeiJiService.selectYbHourLeiJiListGt(id);
            for (int i = 0; i < ybHourLeiJiListGt.size(); i++) {
                YbHourAccumulate ybHourAccumulate = new YbHourAccumulate();
                ybHourAccumulate.setId(Integer.parseInt(ybHourLeiJiListGt.get(i).get("id").toString()));
                ybHourAccumulate.setEndTime(DateUtil.convertLocalDateTime(ybHourLeiJiListGt.get(i).get("StopTime").toString().replace(" ", "T")));
                ybHourAccumulate.setEndValue(Float.parseFloat(ybHourLeiJiListGt.get(i).get("StopValue").toString()));
                ybHourAccumulate.setInstrumentName(ybHourLeiJiListGt.get(i).get("Instrument").toString());
                ybHourAccumulate.setStartTime(DateUtil.convertLocalDateTime(ybHourLeiJiListGt.get(i).get("StartTime").toString().replace(" ", "T")));
                ybHourAccumulate.setStartValue(Float.parseFloat(ybHourLeiJiListGt.get(i).get("StartValue").toString()));
                ybHourAccumulate.setTotal(Float.parseFloat(ybHourLeiJiListGt.get(i).get("Total").toString()));
                accumulateList.add(ybHourAccumulate);
            }
        } else {
            //同步所有数据
            List<Map> ybHourLeiJiListAll = iYbHourLeiJiService.selectYbHourLeiJiListAll();
            for (int i = 0; i < ybHourLeiJiListAll.size(); i++) {
                YbHourAccumulate ybHourAccumulate = new YbHourAccumulate();
                ybHourAccumulate.setId(Integer.parseInt(ybHourLeiJiListAll.get(i).get("id").toString()));
                ybHourAccumulate.setEndTime(DateUtil.convertLocalDateTime(ybHourLeiJiListAll.get(i).get("StopTime").toString().replace(" ", "T")));
                ybHourAccumulate.setEndValue(Float.parseFloat(ybHourLeiJiListAll.get(i).get("StopValue").toString()));
                ybHourAccumulate.setInstrumentName(ybHourLeiJiListAll.get(i).get("Instrument").toString());
                ybHourAccumulate.setStartTime(DateUtil.convertLocalDateTime(ybHourLeiJiListAll.get(i).get("StartTime").toString().replace(" ", "T")));
                ybHourAccumulate.setStartValue(Float.parseFloat(ybHourLeiJiListAll.get(i).get("StartValue").toString()));
                ybHourAccumulate.setTotal(Float.parseFloat(ybHourLeiJiListAll.get(i).get("Total").toString()));
                accumulateList.add(ybHourAccumulate);
            }
        }
        if (accumulateList.size() > 0) {
            ybHourAccumulateMapper.batchInsert(accumulateList);
        }
    }

    //班组累计更新
    public void syncYbClassAccumulateData() {

        //换班后修改实时累计值
        Displaydata displaydata = new Displaydata();
        List<Displaydata> displaydataList = iDisplaydataService.selectList(displaydata);

        for (int i = 0; i < displaydataList.size(); i++) {
            if (displaydataList.get(i).getId() < 6) {
                YbRunAccumulate ybRunAccumulate = iYbRunAccumulateService.selectYbRunAccumulate(displaydataList.get(i).getInstrumentName());
                //修改初始化累计值
                displaydataList.get(i).setInitAccumulate(ybRunAccumulate.getEndValue());
            }
        }
        iDisplaydataService.saveOrUpdateBatch(displaydataList);

        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        List<YbClassesAccumulate> classesAccumulates = new ArrayList<>();
        LocalTime currentTime = LocalTime.now();
        Map<String, YbRunAccumulate> stringYbRunAccumulateMap = new HashMap<>();
        //根据时间区分班组并查询累计值
        if (DateUtil.getBetweenTime(currentTime)) {
            stringYbRunAccumulateMap = iYbRunAccumulateService.selectYbRunAccumulateByClass(1);
        } else {
            stringYbRunAccumulateMap = iYbRunAccumulateService.selectYbRunAccumulateByClass(2);
        }

        //同步数据
        for (int i = 0; i < displaydataList.size(); i++) {
            if (displaydataList.get(i).getId() < 6) {
                YbClassesAccumulate ybClassesAccumulate = new YbClassesAccumulate();

                ybClassesAccumulate.setInstrumentName(displaydataList.get(i).getInstrumentName());
                if(stringYbRunAccumulateMap.get(displaydataList.get(i).getInstrumentName()) != null){
                    ybClassesAccumulate.setClassesValue(stringYbRunAccumulateMap.get(displaydataList.get(i).getInstrumentName()).getTotal());
                } else {
                    ybClassesAccumulate.setClassesValue(0.0f);
                }
                //二班
                if (DateUtil.getBetweenTime(currentTime)) {
                    ybClassesAccumulate.setDateTime(format.format(DateUtil.getYesterdayDate()));
                    ybClassesAccumulate.setClasses(EnviromentConstance.CLASSES_TWO);
                    ybClassesAccumulate.setClassesName(EnviromentConstance.CLASSES_NAME_TWO);
                    ybClassesAccumulate.setModifyTime(DateUtil.getEightOClock());
                    ybClassesAccumulate.setStatisticsDate(DateUtil.getYesterdayDate());
                    classesAccumulates.add(ybClassesAccumulate);
                } else {
                    //一班
                    ybClassesAccumulate.setDateTime(format.format(DateUtil.getNowStatisticDate()));
                    ybClassesAccumulate.setClasses(EnviromentConstance.CLASSES_ONE);
                    ybClassesAccumulate.setClassesName(EnviromentConstance.CLASSES_NAME_ONE);
                    ybClassesAccumulate.setModifyTime(DateUtil.getTwentyOClock());
                    ybClassesAccumulate.setStatisticsDate(DateUtil.getNowStatisticDate());
                    classesAccumulates.add(ybClassesAccumulate);
                }
            }
        }
        if (classesAccumulates.size() > 0) {
            ybClassesAccumulateMapper.batchInsert(classesAccumulates);
            log.info("班组累计对象:{}", classesAccumulates);
        }

    }

    *//**
     * 运行累计
     *//*
    public void syncYbRunAccumulateData() {
        YbRunAccumulate ybRunAccumulateLast = iYbRunAccumulateService.selectYbRunAccumulate("");

        List<YbRunAccumulate> ybRunAccumulates = new ArrayList<>();
        if (ybRunAccumulateLast != null) {
            Integer id = ybRunAccumulateLast.getId();
            List<Map> ybRunLeiJiListGt = iYbRunLeiJiService.selectYbRunLeiJiListGt(id);
            //获取最新数据
            if (ybRunLeiJiListGt.size() > 0) {
                //TODO 更新数据
                for (int i = 0; i < ybRunLeiJiListGt.size(); i++) {
                    YbRunAccumulate ybRunAccumulate = new YbRunAccumulate();
                    ybRunAccumulate.setId(Integer.parseInt(ybRunLeiJiListGt.get(i).get("id").toString()));
                    ybRunAccumulate.setTotal(Float.parseFloat(ybRunLeiJiListGt.get(i).get("Total").toString()));
                    ybRunAccumulate.setEndTime(DateUtil.convertLocalDateTime(ybRunLeiJiListGt.get(i).get("StopTime").toString().replace(" ", "T")));
                    ybRunAccumulate.setInstrumentName(ybRunLeiJiListGt.get(i).get("Instrument").toString());
                    ybRunAccumulate.setStartTime(DateUtil.convertLocalDateTime(ybRunLeiJiListGt.get(i).get("StartTime").toString().replace(" ", "T")));
                    YbRunAccumulate instrument = iYbRunAccumulateService.selectYbRunAccumulate(ybRunLeiJiListGt.get(i).get("Instrument").toString());
                    ybRunAccumulate.setStartValue(instrument.getEndValue());
                    ybRunAccumulate.setEndValue(instrument.getEndValue() + Float.parseFloat(ybRunLeiJiListGt.get(i).get("Total").toString()));
                    ybRunAccumulates.add(ybRunAccumulate);
                }
            }

        } else {
            //获取所有数据
            List<Map> ybRunLeiJiListAll = iYbRunLeiJiService.selectYbRunLeiJiListAll();
            //TODO 更新数据
            for (int i = 0; i < ybRunLeiJiListAll.size(); i++) {
                YbRunAccumulate ybRunAccumulate = new YbRunAccumulate();
                ybRunAccumulate.setId(Integer.parseInt(ybRunLeiJiListAll.get(i).get("id").toString()));
                ybRunAccumulate.setTotal(Float.parseFloat(ybRunLeiJiListAll.get(i).get("Total").toString()));
                ybRunAccumulate.setEndTime(DateUtil.convertLocalDateTime(ybRunLeiJiListAll.get(i).get("StopTime").toString().replace(" ", "T")));
                ybRunAccumulate.setInstrumentName(ybRunLeiJiListAll.get(i).get("Instrument").toString());
                ybRunAccumulate.setEndValue(Float.parseFloat(ybRunLeiJiListAll.get(i).get("StopValue").toString()));
                ybRunAccumulate.setStartTime(DateUtil.convertLocalDateTime(ybRunLeiJiListAll.get(i).get("StartTime").toString().replace(" ", "T")));
                ybRunAccumulate.setStartValue(Float.parseFloat(ybRunLeiJiListAll.get(i).get("StartValue").toString()));
                ybRunAccumulates.add(ybRunAccumulate);

            }
        }
        if (ybRunAccumulates.size() > 0) {
            ybRunAccumulateMapper.batchInsert(ybRunAccumulates);
        }
    }*/
    /* *
     * 页面展示数据更新*/
    public void syncDisplayData() {
        //远程实时数据查询
        EastBeltscalesInstantaneousdata westBeltscalesInstantaneousdata = iEastBeltscalesInstantaneousdataService.selectByLastData();

        Displaydata displaydata = new Displaydata();
        List<Displaydata> displaydataList = iDisplaydataService.selectList(displaydata);
        List<Displaydata> displaydataListSyn = new ArrayList<>();
        //数据同步
        for (int i = 0; i < displaydataList.size(); i++) {
            if (displaydataList.get(i).getId() == 1) {
                displaydataList.get(i).setDataStatus(westBeltscalesInstantaneousdata.getBeltRun1());
                displaydataList.get(i).setFlowValue(westBeltscalesInstantaneousdata.getInstantaneousTraffic1());
                displaydataList.get(i).setSpeedValue(westBeltscalesInstantaneousdata.getSpeed1());
                displaydataList.get(i).setInstrumentName("中文仪表1");
                //displaydataList.get(i).setInstrumentName("西线1号皮带秤");
                //实时计算班累计
                displaydataList.get(i).setClassAccumulation(westBeltscalesInstantaneousdata.getCumulativeFlow1() - displaydataList.get(i).getInitAccumulate());
                //实时计算总累计
                if (displaydataList.get(i).getInitAccumulate() != null) {
                    displaydataList.get(i).setAccumulate(displaydataList.get(i).getInitAccumulate() + displaydataList.get(i).getClassAccumulation());
                }
                displaydataList.get(i).setHourlyAccumulation(westBeltscalesInstantaneousdata.getHourFlow1());
            }
            if (displaydataList.get(i).getId() == 2) {
                displaydataList.get(i).setDataStatus(westBeltscalesInstantaneousdata.getBeltRun2());
                displaydataList.get(i).setFlowValue(westBeltscalesInstantaneousdata.getInstantaneousTraffic2());
                displaydataList.get(i).setSpeedValue(westBeltscalesInstantaneousdata.getSpeed2());
                displaydataList.get(i).setInstrumentName("中文仪表2");
                //displaydataList.get(i).setInstrumentName("西线2号皮带秤");
                //实时计算班累计
                displaydataList.get(i).setClassAccumulation(westBeltscalesInstantaneousdata.getCumulativeFlow2() - displaydataList.get(i).getInitAccumulate());
                //实时计算总累计
                if (displaydataList.get(i).getInitAccumulate() != null) {
                    displaydataList.get(i).setAccumulate(displaydataList.get(i).getInitAccumulate() + displaydataList.get(i).getClassAccumulation());
                }
                displaydataList.get(i).setHourlyAccumulation(westBeltscalesInstantaneousdata.getHourFlow2());
            }
            if (displaydataList.get(i).getId() == 3) {
                displaydataList.get(i).setDataStatus(westBeltscalesInstantaneousdata.getBeltRun3());
                displaydataList.get(i).setFlowValue(westBeltscalesInstantaneousdata.getInstantaneousTraffic3());
                displaydataList.get(i).setSpeedValue(westBeltscalesInstantaneousdata.getSpeed3());
                displaydataList.get(i).setInstrumentName("中文仪表3");
                //displaydataList.get(i).setInstrumentName("西线3号皮带秤");
                //实时计算班累计
                displaydataList.get(i).setClassAccumulation(westBeltscalesInstantaneousdata.getCumulativeFlow3() - displaydataList.get(i).getInitAccumulate());
                //实时计算总累计
                if (displaydataList.get(i).getInitAccumulate() != null) {
                    displaydataList.get(i).setAccumulate(displaydataList.get(i).getInitAccumulate() + displaydataList.get(i).getClassAccumulation());
                }
                displaydataList.get(i).setHourlyAccumulation(westBeltscalesInstantaneousdata.getHourFlow3());
            }
            if (displaydataList.get(i).getId() == 4) {
                displaydataList.get(i).setDataStatus(westBeltscalesInstantaneousdata.getBeltRun4());
                displaydataList.get(i).setFlowValue(westBeltscalesInstantaneousdata.getInstantaneousTraffic4());
                displaydataList.get(i).setSpeedValue(westBeltscalesInstantaneousdata.getSpeed4());
                displaydataList.get(i).setInstrumentName("中文仪表4");
                //displaydataList.get(i).setInstrumentName("西线4号皮带秤");
                //实时计算班累计
                displaydataList.get(i).setClassAccumulation(westBeltscalesInstantaneousdata.getCumulativeFlow4() - displaydataList.get(i).getInitAccumulate());
                //实时计算总累计
                if (displaydataList.get(i).getInitAccumulate() != null) {
                    displaydataList.get(i).setAccumulate(displaydataList.get(i).getInitAccumulate() + displaydataList.get(i).getClassAccumulation());
                }
                displaydataList.get(i).setHourlyAccumulation(westBeltscalesInstantaneousdata.getHourFlow4());
            }
            if (displaydataList.get(i).getId() == 5) {
                displaydataList.get(i).setDataStatus(westBeltscalesInstantaneousdata.getBeltRun5());
                displaydataList.get(i).setFlowValue(westBeltscalesInstantaneousdata.getInstantaneousTraffic5());
                displaydataList.get(i).setSpeedValue(westBeltscalesInstantaneousdata.getSpeed5());
                displaydataList.get(i).setInstrumentName("中文仪表5");
                //displaydataList.get(i).setInstrumentName("西线5号皮带秤");
                //实时计算班累计
                displaydataList.get(i).setClassAccumulation(westBeltscalesInstantaneousdata.getCumulativeFlow5() - displaydataList.get(i).getInitAccumulate());
                //实时计算总累计
                if (displaydataList.get(i).getInitAccumulate() != null) {
                    displaydataList.get(i).setAccumulate(displaydataList.get(i).getInitAccumulate() + displaydataList.get(i).getClassAccumulation());
                }
                displaydataList.get(i).setHourlyAccumulation(westBeltscalesInstantaneousdata.getHourFlow5());
            }
            displaydataListSyn.add(displaydataList.get(i));
        }
        iDisplaydataService.saveOrUpdateBatch(displaydataListSyn);

        //仪表开关
        for (int i = 0; i < displaydataList.size(); i++) {
            if (displaydataList.get(i).getSwitchStatus() != null && !iInstrumentControlService.getInstrumentStatus().get(displaydataList.get(i).getId()).equals(displaydataList.get(i).getSwitchStatus().toString())) {
                //开关状态同步
                displaydataList.get(i).setSwitchStatus(Integer.parseInt(iInstrumentControlService.getInstrumentStatus().get(displaydataList.get(i).getId())));
                //关闭时同步当前数据到Copy
                if (iInstrumentControlService.getInstrumentStatus().get(displaydataList.get(i).getId()).equals(EnviromentConstance.IS_NOT_ENABLE)) {
                    displaydataList.get(i).setAccumulateCopy(displaydataList.get(i).getAccumulate());
                    displaydataList.get(i).setClassAccumulationCopy(displaydataList.get(i).getClassAccumulation());
                    displaydataList.get(i).setDayAccumulationCopy(displaydataList.get(i).getDayAccumulation());
                    displaydataList.get(i).setHourlyAccumulationCopy(displaydataList.get(i).getHourlyAccumulation());
                    displaydataList.get(i).setFlowValueCopy(0.0f);
                    displaydataList.get(i).setSpeedValueCopy(0.0f);
                }
                iDisplaydataService.saveOrUpdate(displaydataList.get(i));
            }
        }
        List<Map<String, String>> resultMaps = new ArrayList<>();


        for (int i = 0; i < displaydataList.size(); i++) {
            //开关关闭状态
            if (displaydataList.get(i).getSwitchStatus() != null && displaydataList.get(i).getSwitchStatus() == 0) {
                Map<String, String> map = new HashMap<>();
                map.put("id", displaydataList.get(i).getId().toString());
                map.put("instrumentName", displaydataList.get(i).getInstrumentName());
                map.put("accumulate", displaydataList.get(i).getAccumulateCopy().toString());
                map.put("flowValue", displaydataList.get(i).getFlowValueCopy().toString());
                map.put("speedValue", displaydataList.get(i).getSpeedValueCopy().toString());
                map.put("hourlyAccumulation", displaydataList.get(i).getHourlyAccumulationCopy().toString());
                map.put("classAccumulation", displaydataList.get(i).getClassAccumulationCopy().toString());
                resultMaps.add(map);
                //开关打开状态
            } else if (displaydataList.get(i).getSwitchStatus() != null && displaydataList.get(i).getSwitchStatus() == 1) {
                Map<String, String> map = new HashMap<>();
                map.put("id", displaydataList.get(i).getId().toString());
                map.put("instrumentName", displaydataList.get(i).getInstrumentName());
                map.put("accumulate", displaydataList.get(i).getAccumulate().toString());
                map.put("flowValue", displaydataList.get(i).getFlowValue().toString());
                map.put("speedValue", displaydataList.get(i).getSpeedValue().toString());
                map.put("hourlyAccumulation", displaydataList.get(i).getHourlyAccumulation().toString());
                map.put("classAccumulation", displaydataList.get(i).getClassAccumulation().toString());
                resultMaps.add(map);
            }
        }

        //组装配料比例
        List<Float> floats = new ArrayList<>();
        floats.add(westBeltscalesInstantaneousdata.getSetValue1());
        floats.add(westBeltscalesInstantaneousdata.getSetValue2());
        floats.add(westBeltscalesInstantaneousdata.getSetValue3());
        floats.add(westBeltscalesInstantaneousdata.getSetValue4());
        floats.add(westBeltscalesInstantaneousdata.getSetValue5());
        for (int i = 0; i < floats.size(); i++) {
            resultMaps.get(i).put("setTraffic", floats.get(i).toString());
        }


        List<Map> resultMapList = new ArrayList<>();
        Map<String, String> collect = resultMaps.stream()
                .collect(Collectors.toMap(
                        map -> map.get("id"),
                        map -> map.get("instrumentName")
                ));
        resultMapList.add(collect);
        Map<String, String> collect1 = resultMaps.stream()
                .collect(Collectors.toMap(
                        map -> map.get("id"),
                        map -> map.get("accumulate")
                ));
        resultMapList.add(collect1);
        Map<String, String> collect2 = resultMaps.stream()
                .collect(Collectors.toMap(
                        map -> map.get("id"),
                        map -> map.get("flowValue")
                ));
        resultMapList.add(collect2);
        Map<String, String> collect3 = resultMaps.stream()
                .collect(Collectors.toMap(
                        map -> map.get("id"),
                        map -> map.get("speedValue")
                ));
        resultMapList.add(collect3);

        Map<String, String> collect7 = resultMaps.stream()
                .collect(Collectors.toMap(
                        map -> map.get("id"),
                        map -> map.get("setTraffic")
                ));
        resultMapList.add(collect7);

        Map<String, String> collect4 = resultMaps.stream()
                .collect(Collectors.toMap(
                        map -> map.get("id"),
                        map -> map.get("hourlyAccumulation")
                ));
        resultMapList.add(collect4);
        Map<String, String> collect5 = resultMaps.stream()
                .collect(Collectors.toMap(
                        map -> map.get("id"),
                        map -> map.get("classAccumulation")
                ));
        resultMapList.add(collect5);


        //发送websocket消息
        ResultMsg msg = new ResultMsg();
        msg.setCode("200");
        msg.setMessage(resultMapList);
        NettySendUtil.sendAllMessage(msg, MyChannelHandlerPool.channelGroup);
    }

    //分钟数据更新
    public void syncIsLqxData() {
        ScaleData scaleDataLast = iScaleDataService.selectScaleData();

        List<ScaleData> scaleDataList = new ArrayList<>();
        if (scaleDataLast != null) {
            Integer id = Integer.parseInt(scaleDataLast.getId());
            List<EastBeltscalesMinitue> eastBeltscalesMinitues = iEastBeltscalesMinitueService.selectEastBeltsCalesMinitueListGt(id);
            //同步最新数据
            if (eastBeltscalesMinitues.size() > 0) {
                for (int i = 0; i < eastBeltscalesMinitues.size(); i++) {
                    ScaleData scaleData = new ScaleData();
                    scaleData.setId(eastBeltscalesMinitues.get(i).getId().toString());
                    scaleData.setCreateTime(eastBeltscalesMinitues.get(i).getDatetime());
                    scaleData.setB1(eastBeltscalesMinitues.get(i).getInstantaneousTraffic1());
                    scaleData.setB2(eastBeltscalesMinitues.get(i).getInstantaneousTraffic2());
                    scaleData.setB3(eastBeltscalesMinitues.get(i).getInstantaneousTraffic3());
                    scaleData.setB4(eastBeltscalesMinitues.get(i).getInstantaneousTraffic4());
                    scaleData.setB5(eastBeltscalesMinitues.get(i).getInstantaneousTraffic5());
                    scaleDataList.add(scaleData);
                }
            }
        } else {
            //同步所有数据
            EastBeltscalesMinitue eastBeltscalesMinitues = new EastBeltscalesMinitue();
            List<EastBeltscalesMinitue> eastBeltscalesMinituesList = iEastBeltscalesMinitueService.selectList(eastBeltscalesMinitues);
            for (int i = 0; i < eastBeltscalesMinituesList.size(); i++) {
                ScaleData scaleData = new ScaleData();
                scaleData.setId(eastBeltscalesMinituesList.get(i).getId().toString());
                scaleData.setCreateTime(eastBeltscalesMinituesList.get(i).getDatetime());
                scaleData.setB1(eastBeltscalesMinituesList.get(i).getInstantaneousTraffic1());
                scaleData.setB2(eastBeltscalesMinituesList.get(i).getInstantaneousTraffic2());
                scaleData.setB3(eastBeltscalesMinituesList.get(i).getInstantaneousTraffic3());
                scaleData.setB4(eastBeltscalesMinituesList.get(i).getInstantaneousTraffic4());
                scaleData.setB5(eastBeltscalesMinituesList.get(i).getInstantaneousTraffic5());
                scaleDataList.add(scaleData);
            }
        }
        if (scaleDataList.size() > 100000) {
            List<List<ScaleData>> partition = Lists.partition(scaleDataList, 1000);
            for (List<ScaleData> list : partition) {
                scaleDataMapper.batchInsert(list);
            }
        } else if (scaleDataList.size() < 100000 && scaleDataList.size() > 0) {
            scaleDataMapper.batchInsert(scaleDataList);
        }

    }

    /**
     * 运行累计
     */

    public void syncYbRunAccumulateData() {
        //查询仪表运行最后一条数据
        YbRunAccumulate ybRunAccumulateLast = iYbRunAccumulateService.selectYbRunAccumulate("");

        List<YbRunAccumulate> ybRunAccumulates = new ArrayList<>();
        if (ybRunAccumulateLast != null) {
            Integer id = ybRunAccumulateLast.getId();
            //查询远程最后一条数据
            List<EastBeltscalesCumulativedata> eastBeltscalesCumulativedata = iEastBeltscalesCumulativedataService.selectEastBeltsCalesCumulativeDataListGt(id);
            if (eastBeltscalesCumulativedata.size() > 0) {
                //同步远程数据
                //TODO 更新数据
                for (int i = 0; i < eastBeltscalesCumulativedata.size(); i++) {
                    YbRunAccumulate ybRunAccumulate = new YbRunAccumulate();
                    ybRunAccumulate.setId(eastBeltscalesCumulativedata.get(i).getId().intValue());
                    ybRunAccumulate.setTotal(eastBeltscalesCumulativedata.get(i).getTotalValue());
                    ybRunAccumulate.setEndTime(eastBeltscalesCumulativedata.get(i).getEndTime());
                    ybRunAccumulate.setInstrumentName(eastBeltscalesCumulativedata.get(i).getName());
                    ybRunAccumulate.setStartTime(eastBeltscalesCumulativedata.get(i).getStartTime());
                    YbRunAccumulate instrument = iYbRunAccumulateService.selectYbRunAccumulate(eastBeltscalesCumulativedata.get(i).getName());
                    ybRunAccumulate.setStartValue(instrument.getEndValue());
                    ybRunAccumulate.setEndValue(instrument.getEndValue() + eastBeltscalesCumulativedata.get(i).getTotalValue());
                    ybRunAccumulates.add(ybRunAccumulate);
                }
            }

        } else {
            //同步远程所有仪表运行数据
            List<EastBeltscalesCumulativedata> eastBeltscalesCumulativedata = iEastBeltscalesCumulativedataService.selectYbRunLeiJiListAll();
            //List<Map> maps = fieldControl(hktsHeatItems, ybRunLeiJiListAll);
            //TODO 更新数据
            for (int i = 0; i < eastBeltscalesCumulativedata.size(); i++) {
                YbRunAccumulate ybRunAccumulate = new YbRunAccumulate();
                ybRunAccumulate.setId(eastBeltscalesCumulativedata.get(i).getId().intValue());
                ybRunAccumulate.setTotal(eastBeltscalesCumulativedata.get(i).getTotalValue());
                ybRunAccumulate.setEndTime(eastBeltscalesCumulativedata.get(i).getEndTime());
                ybRunAccumulate.setInstrumentName(eastBeltscalesCumulativedata.get(i).getName());
                ybRunAccumulate.setEndValue(eastBeltscalesCumulativedata.get(i).getEndValue());
                ybRunAccumulate.setStartTime(eastBeltscalesCumulativedata.get(i).getStartTime());
                ybRunAccumulate.setStartValue(eastBeltscalesCumulativedata.get(i).getStartValue());
                ybRunAccumulates.add(ybRunAccumulate);

            }
        }
        if (ybRunAccumulates.size() > 0) {
            ybRunAccumulateMapper.batchInsert(ybRunAccumulates);
        }
    }

    //班组累计更新
    public void syncYbClassAccumulateData() {

        //换班后修改实时累计值
        Displaydata displaydata = new Displaydata();
        List<Displaydata> displaydataList = iDisplaydataService.selectList(displaydata);
        for (int i = 0; i < displaydataList.size(); i++) {
            YbRunAccumulate ybRunAccumulate = iYbRunAccumulateService.selectYbRunAccumulate(displaydataList.get(i).getInstrumentName());
            //修改初始化累计值
            displaydataList.get(i).setInitAccumulate(ybRunAccumulate.getEndValue());
        }
        iDisplaydataService.saveOrUpdateBatch(displaydataList);

        List<YbClassesAccumulate> classesAccumulates = new ArrayList<>();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        LocalTime currentTime = LocalTime.now();
        Map<String, YbRunAccumulate> stringYbRunAccumulateMap = new HashMap<>();
        //根据时间区分班组并查询班累计总值
        if (DateUtil.getBetweenTime(currentTime)) {
            stringYbRunAccumulateMap = iYbRunAccumulateService.selectYbRunAccumulateByClass(1);
        } else {
            stringYbRunAccumulateMap = iYbRunAccumulateService.selectYbRunAccumulateByClass(2);
        }
        for (int i = 0; i < displaydataList.size(); i++) {
            YbClassesAccumulate ybClassesAccumulate = new YbClassesAccumulate();
            ybClassesAccumulate.setInstrumentName(displaydataList.get(i).getInstrumentName());
            //班累计总值
            if(stringYbRunAccumulateMap.get(displaydataList.get(i).getInstrumentName()) != null){
                ybClassesAccumulate.setClassesValue(stringYbRunAccumulateMap.get(displaydataList.get(i).getInstrumentName()).getTotal());
            } else {
                ybClassesAccumulate.setClassesValue(0.0f);
            }
            //二班
            if (DateUtil.getBetweenTime(currentTime)) {
                ybClassesAccumulate.setDateTime(format.format(DateUtil.getYesterdayDate()));
                ybClassesAccumulate.setClasses(EnviromentConstance.CLASSES_TWO);
                ybClassesAccumulate.setClassesName(EnviromentConstance.CLASSES_NAME_TWO);
                ybClassesAccumulate.setModifyTime(DateUtil.getEightOClock());
                ybClassesAccumulate.setStatisticsDate(DateUtil.getYesterdayDate());
                classesAccumulates.add(ybClassesAccumulate);
            } else {
                //一班
                ybClassesAccumulate.setDateTime(format.format(DateUtil.getNowStatisticDate()));
                ybClassesAccumulate.setClasses(EnviromentConstance.CLASSES_ONE);
                ybClassesAccumulate.setClassesName(EnviromentConstance.CLASSES_NAME_ONE);
                ybClassesAccumulate.setModifyTime(DateUtil.getTwentyOClock());
                ybClassesAccumulate.setStatisticsDate(DateUtil.getNowStatisticDate());
                classesAccumulates.add(ybClassesAccumulate);
            }
        }
        if (classesAccumulates.size() > 0) {
            ybClassesAccumulateMapper.batchInsert(classesAccumulates);
            log.info("班组累计对象:{}", classesAccumulates);
        }

    }

    public void contrField() {
        //计算总值是否大于标准值
        LocalTime currentTime = LocalTime.now();
        //TODO 判断是否有新增数据
        //获取数据库最后一条数据
        YbRunAccumulate ybRunAccumulateLast = iYbRunAccumulateService.selectYbRunAccumulate("");
        if (RunTimeCache.dateTimeMap.get("id") == null) {

            RunTimeCache.dateTimeMap.put("id", ybRunAccumulateLast.getId());
        } else {
            //判断当前的id是否大于缓存的id
            if (ybRunAccumulateLast.getId() > RunTimeCache.dateTimeMap.get("id")) {
                //在8点-20点之间
                if (DateUtil.getBetweenTime(currentTime)) {
                    //查询大于8.的所有的运行数据
                    List<YbRunAccumulate> ybRunAccumulateList = iYbRunAccumulateService.selectBetweenList(1);
                    //排序
                    Map<String, List<YbRunAccumulate>> collect = ybRunAccumulateList.stream()
                            .collect(Collectors.groupingBy(YbRunAccumulate::getInstrumentName));
                    Map<String, List<YbRunAccumulate>> resultMap = new TreeMap<>(collect);
                    //获取随机数
                    RandomNumberSettings byId = iRandomNumberSettingsService.getById(1);

                    Float random = SnowFlakeUtil.getRandom(byId.getStartValue() * byId.getCoefficient(), byId.getEndValue() * byId.getCoefficient());
                    log.info("随机数为:{}", random);
                    //计算所有数的总和
                    double sum = ybRunAccumulateList.stream()
                            .flatMapToDouble(ybRunAccumulate -> DoubleStream.of(ybRunAccumulate.getTotal()))
                            .sum();
                    //总数大于最大数
                    if (sum > byId.getEndValue() * byId.getCoefficient()) {
                        //求出比率
                        Float v = random / (float) sum;

                        for (Map.Entry<String, List<YbRunAccumulate>> entry : resultMap.entrySet()) {
                            //源数据乘系数并计算下一条
                            List<YbRunAccumulate> value = entry.getValue();
                            for (int i = 0; i < value.size(); i++) {
                                Float v1 = value.get(i).getTotal() * v;
                                value.get(i).setTotal(v1);
                                value.get(i).setEndValue(value.get(i).getStartValue() + v1);
                                if (i + 1 < value.size() && value.size() > 1) {
                                    value.get(i + 1).setStartValue(value.get(i).getStartValue() + v1);
                                }
                            }
                            iYbRunAccumulateService.saveOrUpdateBatch(value);
                        }

                    }

                } else {
                    // 获取当天的20点整
                    List<YbRunAccumulate> ybRunAccumulateList = iYbRunAccumulateService.selectBetweenList(2);
                    Map<String, List<YbRunAccumulate>> collect = ybRunAccumulateList.stream()
                            .collect(Collectors.groupingBy(YbRunAccumulate::getInstrumentName));
                    Map<String, List<YbRunAccumulate>> resultMap = new TreeMap<>(collect);
                    RandomNumberSettings byId = iRandomNumberSettingsService.getById(2);
                    Float random = SnowFlakeUtil.getRandom(byId.getStartValue() * byId.getCoefficient(), byId.getEndValue() * byId.getCoefficient());
                    log.info("随机数为:{}", random);
                    double sum = ybRunAccumulateList.stream()
                            .flatMapToDouble(ybRunAccumulate -> DoubleStream.of(ybRunAccumulate.getTotal()))
                            .sum();
                    //总数大于最大数
                    if (sum > byId.getEndValue() * byId.getCoefficient()) {
                        //求出比例
                        Float v = random / (float) sum;
                        for (Map.Entry<String, List<YbRunAccumulate>> entry : resultMap.entrySet()) {

                            List<YbRunAccumulate> value = entry.getValue();
                            //源数据乘系数并计算下一条
                            for (int i = 0; i < value.size(); i++) {
                                Float v1 = value.get(i).getTotal() * v;
                                value.get(i).setTotal(v1);
                                value.get(i).setEndValue(value.get(i).getStartValue() + v1);
                                if (i + 1 < value.size() && value.size() > 1) {
                                    value.get(i + 1).setStartValue(value.get(i).getStartValue() + v1);
                                }
                            }
                            iYbRunAccumulateService.saveOrUpdateBatch(value);
                        }
                    }
                }
                RunTimeCache.dateTimeMap.put("id", ybRunAccumulateLast.getId());
            }
        }
    }

    //定时修改系数
    public void coefficientControlByTime(){
        //查询是否有提前设置好的系数
        RegularTime regularTime = iRegularTimeService.selectByStatus();
        if (regularTime != null && LocalDateTime.now().isAfter(regularTime.getStartTime())){
            iRandomNumberSettingsService.randomNumberSettingsUpdate(regularTime.getCoefficientf());
            regularTime.setStatus(1);
            iRegularTimeService.saveOrUpdate(regularTime);
        }
    }
}
